import styled from '@emotion/styled';
import { Alert, Drawer, Form, Input, Modal, Tooltip } from 'antd';
import { cloneElement, FC, ReactNode } from 'react';

import EditIcon from '@/assets/icons/edit.svg';
import { useCurrentNode } from '@/hooks/useCurrentNode';
import { useMode } from '@/store/mode';
import { useNodeResults } from '@/store/node-results';

import { BaseNodeContent } from '../BaseNode';

interface NodeDrawerProps {
  size?: number | string;
  title?: ReactNode;
  placement?: 'top' | 'right' | 'bottom' | 'left';
  children: ReactNode;
  onOpen?: () => void;
  trigger?: ReactNode;
}

const DrawerStyled = styled(Drawer)`
  .ant-drawer-body {
    padding: 0px 12px;
  }
`;

export const NodeDrawer: FC<NodeDrawerProps> = memo((props) => {
  const { mode } = useMode();
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);
  const [renameVisible, setRenameVisible] = useState(false);
  const { setActiveNodeId, currentNodeData, setNodeData } = useCurrentNode();
  const nodeName = currentNodeData?.nodeName;
  const { hasExecResult } = useNodeResults();

  const editNodeName = () => {
    form
      .validateFields()
      .then((values) => {
        setNodeData({ nodeName: values.nodeName });
        form.resetFields();
        setRenameVisible(false);
      })
      .catch(() => {});
  };

  return (
    <>
      {props.trigger &&
        cloneElement(props.trigger as any, {
          onClick() {
            setVisible(true);
            props.onOpen?.();
          }
        })}

      <DrawerStyled
        placement={props.placement || 'right'}
        destroyOnClose
        height={props.size || 600}
        width={props.size || 800}
        open={visible}
        title={
          props.title ? (
            props.title
          ) : (
            <BaseNodeContent
              className="h-20"
              nodeNameEditable
              nodeName={nodeName || '未命名'}
              nodeType={currentNodeData.nodeType!}>
              {mode === 'edit' && (
                <Tooltip title="修改节点名称" placement="bottom">
                  <div className="flex items-center">
                    <EditIcon
                      onClick={() => setRenameVisible(true)}
                      name="edit"
                      className="w-16 h-16 ml-12 cursor-pointer node-name-editable"
                    />
                  </div>
                </Tooltip>
              )}
            </BaseNodeContent>
          )
        }
        onClose={() => {
          setActiveNodeId('');
          setVisible(false);
        }}>
        <div className="node-drawer mx-auto pt-12">
          {hasExecResult && <Alert message="当前处于测试不可编辑模式" type="info" showIcon />}
          {props.children}
        </div>
      </DrawerStyled>

      <Modal
        destroyOnClose
        title="修改节点名称"
        open={renameVisible}
        onOk={editNodeName}
        onCancel={() => {
          setRenameVisible(false);
          form.resetFields();
        }}>
        <Form form={form}>
          <Form.Item label="节点名称" name="nodeName" rules={[{ required: true, message: '请输入节点名称' }]}>
            <Input placeholder="节点名称" />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
});
